package com.example.fastjetpack

import android.app.Application
import androidx.hilt.work.HiltWorkerFactory
import androidx.work.Configuration
import com.example.fastjetpack.base.utils.ErrorHandler
import com.squareup.leakcanary.LeakCanary
import com.taobao.sophix.SophixManager
import com.taobao.update.adapter.UpdateAdapter
import com.taobao.update.apk.ApkUpdater
import com.taobao.update.common.Config
import com.taobao.update.common.framework.UpdateRuntime
import com.taobao.update.datasource.UpdateDataSource
import com.tencent.bugly.Bugly
import dagger.hilt.android.HiltAndroidApp
import io.reactivex.plugins.RxJavaPlugins
import javax.inject.Inject


@HiltAndroidApp
class App : Application() , Configuration.Provider{
    @Inject
    lateinit var workerFactory: HiltWorkerFactory

    override fun onCreate() {
        super.onCreate()
        self = this

        RxJavaPlugins.setErrorHandler(ErrorHandler.TOAST_ERROR_HANDLER)

        initLeakCanary()
        initBugly()
        initSophix()
        initUpdate()
    }

    private fun initUpdate() {
        //以下引号部分需要客户根据自己的应用进行配置（）
        val config = Config()
        config.group = "333421961" + "@android" //填写appkey
        config.ttid = "渠道号" //渠道号
        config.isOutApk = false
        config.appName = resources.getString(R.string.app_name) //app name
        UpdateRuntime.init(this, config.ttid, config.appName, config.group)
        val apkupdate = ApkUpdater(applicationContext, "333421961", "750df6f7723f47f18a5b00842c0ae54b", config.group, "渠道号", config.ttid)
        val updateAdapter = UpdateAdapter()
        UpdateDataSource.getInstance().init(this, config.group, config.ttid, config.isOutApk, "333421961", "750df6f7723f47f18a5b00842c0ae54b", "渠道号", updateAdapter)
        UpdateDataSource.getInstance().startUpdate(false)
    }

    /**
     * 内存溢出监控
     */
    private fun initLeakCanary(){
        if (LeakCanary.isInAnalyzerProcess(this)) {
            return
        }
        LeakCanary.install(this)
    }

    /**
     * emas 热更新
     */
    private fun initSophix() {
        //下载补丁 queryAndLoadNewPatch不可放在attachBaseContext 中，否则无网络权限，建议放在后面任意时刻，如onCreate中
        SophixManager.getInstance().queryAndLoadNewPatch()
    }

    /**
     * bugly全量升级+异常监控
     */
    private fun initBugly() {
        Bugly.init(applicationContext, "4e70a8be04", true)
    }

    companion object {
        @JvmField
        var self: App? = null

        //emas key+秘钥
        const val DEFAULT_APPKEY = "xxxx"
        const val DEFAULT_APPSECRET = "xxxxx"
    }

    override fun getWorkManagerConfiguration() = Configuration.Builder()
            .setWorkerFactory(workerFactory)
            .build()
}